package com.food.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.imagerecog20190930.models.RecognizeFoodResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.food.service.DistinguishService;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author beixiang
 * @version 1.0
 * @description TODO
 * @date 2023/4/24 11:12
 */
@Service
public class DistinguishServiceImpl implements DistinguishService {

    @Value("${minio.endpoint}")
    private String endpoint;

    private String fileBucketName="test";

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * 识图方法
     * @param file
     * @return
     */
    @Override
    public String getDistinguishService(MultipartFile file)  {

        String imgText=null;
        try {
        // "YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET" 的生成请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您是用的子账号AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        com.aliyun.imagerecog20190930.Client client = createClient("LTAI5tJLPczecfseDcD5VNjT", "8KqdTF2n8rToKdzMHJ5kcQp2fmSFPT");
        // 场景一，使用本地文件
        // InputStream inputStream = new FileInputStream(new File("/tmp/RecognizeFood.jpg"));
        // 场景二，使用任意可访问的url
//        URL url = new URL(imgUrl);
//        InputStream inputStream = url.openConnection().getInputStream();
        InputStream inputStream=file.getInputStream();

        com.aliyun.imagerecog20190930.models.RecognizeFoodAdvanceRequest recognizeFoodAdvanceRequest = new com.aliyun.imagerecog20190930.models.RecognizeFoodAdvanceRequest()
                .setImageURLObject(inputStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            RecognizeFoodResponse recognizeFoodAdvanceResponse = client.recognizeFoodAdvance(recognizeFoodAdvanceRequest, runtime);
            // 获取整体结果。
            JSONObject jsonObj = new JSONObject(TeaModel.buildMap(recognizeFoodAdvanceResponse));
            List<Map<String, Object>> list= (List<Map<String, Object>>) jsonObj.getJSONObject("body").getJSONObject("Data").get("TopFives");
            JSONObject jsonObj1 = new JSONObject(list.get(0));
            imgText= (String) jsonObj1.get("Category");
//            System.out.println(jsonObj1.get("Category"));
        } catch (Exception teaException) {
            // 获取整体报错信息。
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
        }
        return imgText;

//        if (file == null) {
//            System.out.println("出错");
//            return null;
//
//        }
//        try {
//
//            MinioClient minioClient = getMinioClient(fileBucketName);
////            String objectName = getFileName(file);
//            String objectName ="智能识图"+".jpg";
//            // 使用putObject上传一个文件到存储桶中。
//            minioClient.putObject(fileBucketName, objectName, file.getInputStream(), file.getContentType());
//            //  可以在浏览器上直接访问的地址
//            //  在这里要注意的是，刚上传时，图片是不能直接访问的，要去minio服务器中，添加对应的桶的权限，然后重启minio服务器
//            //  点击桶右边的三个点 -> Edit policy -> ADD -> Read and Write -> 重启minio 服务器
//            String objectUrl = minioClient.getObjectUrl(fileBucketName, objectName);
////            System.out.println(objectUrl);
//            //获得识别图片后的信息
//            String alibabaPicture = getAlibabaPicture(objectUrl);
//
//            return alibabaPicture;
//        } catch(Exception e) {
////            return ResultUtil.fail(ResultEnum.FAIL_FILE_UPLOAD);
//            System.out.println("出错");
//            return null;
//
//        }
    }

    /**
     * 调用阿里的识图接口
     * @param imgUrl
     * @return
     * @throws Exception
     */
   /* public String getAlibabaPicture(String imgUrl) throws Exception {

       String imgText=null;
        // "YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET" 的生成请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您是用的子账号AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        com.aliyun.imagerecog20190930.Client client = createClient("LTAI5tJLPczecfseDcD5VNjT", "8KqdTF2n8rToKdzMHJ5kcQp2fmSFPT");
        // 场景一，使用本地文件
        // InputStream inputStream = new FileInputStream(new File("/tmp/RecognizeFood.jpg"));
        // 场景二，使用任意可访问的url
        URL url = new URL(imgUrl);
        InputStream inputStream = url.openConnection().getInputStream();
        com.aliyun.imagerecog20190930.models.RecognizeFoodAdvanceRequest recognizeFoodAdvanceRequest = new com.aliyun.imagerecog20190930.models.RecognizeFoodAdvanceRequest()
                .setImageURLObject(inputStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            RecognizeFoodResponse recognizeFoodAdvanceResponse = client.recognizeFoodAdvance(recognizeFoodAdvanceRequest, runtime);
            // 获取整体结果。
            JSONObject jsonObj = new JSONObject(TeaModel.buildMap(recognizeFoodAdvanceResponse));
            List<Map<String, Object>> list= (List<Map<String, Object>>) jsonObj.getJSONObject("body").getJSONObject("Data").get("TopFives");
            JSONObject jsonObj1 = new JSONObject(list.get(0));
            imgText= (String) jsonObj1.get("Category");
//            System.out.println(jsonObj1.get("Category"));
        } catch (TeaException teaException) {
            // 获取整体报错信息。
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // 获取单个字段。
            System.out.println(teaException.getCode());
        }
      return imgText;
    }*/

    /**
     * 访问阿里的接口
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    public  com.aliyun.imagerecog20190930.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imagerecog20190930.Client(config);
    }
    /**
     * 获取 minio 的链接
     * @return  minio链接
     * @throws Exception
     */
  /*  private MinioClient getMinioClient(String bucketName) throws Exception {
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);

        // 检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(bucketName);
        if(!isExist) {
            // 创建一个名为 bucketName 的存储桶
            minioClient.makeBucket(bucketName);
            minioClient.setBucketPolicy(bucketName, ".", PolicyType.READ_ONLY);
        }
        return minioClient;
    }*/
}
